import React, { Suspense } from "react";
import { Layout, Button, Card, Divider, Tooltip, Icon, DatePicker, Select, Form, Row, Col } from "antd";
import Header from "@/layouts/Header";
import { connect } from "dva";
import { formatMessage } from 'umi-plugin-react/locale';
import styles from "../User/Home.less";

import moment from "moment";
import UserSession from "@/UserSession";
import { getIndexInfo } from "@/services/user";
import { getKnowledgeInfo, getDataStat, doHotQuestion } from "@/services/home";

import DataStatic from "../User/dataStatic";
import ChatStat from "../User/chatStat";
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import { doRobotList } from "@/services/robotManagement";
import AccessTrends from "@/pages/DataStatistics/AccessTrends/Index";

const { Content, Sider } = Layout;

class Home extends React.Component {
  state = {
    dataLoading: false,
    dataInfo: {
      visitNum: 0,
      questionNum: 0,
      answerRatio: '0',
      solveRatio: '0',
      transferRatio: '0'
    },
    questionTypeList: [],
    hotList: [],
    tableLoading: false,
    qaTotal: 0,
    total: 0,
    robotList: []
  };

  componentDidMount() {
    const currentUser = UserSession.getCurrentUser();
    if (!currentUser.username) {
      this.props.history.push("/user/login");
    };
    this.getRobot();
    this.getDataInfo();
    this.getHotList();
  }

  /**
   * 获取所有机器人（作为筛选条件）
   */
  getRobot = async () => {
    const res = await doRobotList({ current: 1, size: 999999 });
    this.setState({ robotList: res });
  }

  getDataInfo = () => {
    const currentUser = UserSession.getCurrentUser();
    this.setState({ dataLoading: true }, async () => {
      const formInfo = this.props.form.getFieldsValue()
      let obj = {
        applicationId: currentUser.applicationId ? currentUser.applicationId : formInfo.applicationId,
        trigger: formInfo.trigger,
        fromDate: formInfo.time && formInfo.time[0] ? moment(formInfo.time[0]).format("YYYY-MM-DD") : '',
        toDate: formInfo.time && formInfo.time[1] ? moment(formInfo.time[1]).format("YYYY-MM-DD") : '',
      };
      this.AccessTrends.timeFalseDate(obj)
      const res = await getDataStat(obj);
      let sessionObj = {
        x: res.visit.spread.map(item => item.x),
        y: res.visit.spread.map(item => item.y),
      };
      let transferObj = {
        x: res.transferLabor.spread.map(item => item.x),
        y: res.transferLabor.spread.map(item => item.y),
      };
      let questionTypeList = [];
      let qaTotal = 0;
      for (const item of res.questionType) {
        questionTypeList.push({ value: item.y, name: item.x });
        qaTotal += item.y;
      };
      this.setState({
        dataLoading: false,
        dataInfo: {
          visitNum: res.visit.num,
          questionNum: res.question.num,
          answerRatio: res.answerRatio,
          solveRatio: res.solveRatio,
          transferRatio: res.transferRatio
        },
        questionTypeList,
        qaTotal,
      }, () => {
        this.ChatStat.sessionMain(sessionObj)
        this.ChatStat.pieMain(questionTypeList)
      })
    })
  }

  getHotList = () => {
    const currentUser = UserSession.getCurrentUser();
    this.setState({ tableLoading: true }, async () => {
      const formInfo = this.props.form.getFieldsValue()
      let obj = {
        applicationId: currentUser.applicationId ? currentUser.applicationId : formInfo.applicationId,
        trigger: formInfo.trigger,
        fromDate: formInfo.time && formInfo.time[0] ? moment(formInfo.time[0]).format("YYYY-MM-DD") : '',
        toDate: formInfo.time && formInfo.time[1] ? moment(formInfo.time[1]).format("YYYY-MM-DD") : '',
      };
      const res = await doHotQuestion(obj);
      this.setState({ hotList: res, total: res.total });
    })
  }

  queryByConditions = () => {
    this.getDataInfo();
    this.getHotList();
  }

  quickDate = (amount, unit) => {
    const fromDate = moment().subtract(amount, unit);
    const toDate = moment();
    this.props.form.setFieldsValue({ time: [fromDate, toDate] });
  }

  render() {
    const { currentUser: { username, validity, reviewStatus, overdue }, form: { getFieldDecorator, getFieldValue } } = this.props;
    const { robotList, dataLoading, dataInfo, sessionStat, questionTypeList, hotList, qaTotal, total } = this.state;
    const startTime = getFieldValue("time") && getFieldValue("time")[0] ? moment(getFieldValue("time")[0]).format("YYYY-MM-DD") : '';
    const endTime = getFieldValue("time") && getFieldValue("time")[1] ? moment(getFieldValue("time")[1]).format("YYYY-MM-DD") : '';
    const currentUser = UserSession.getCurrentUser();

    return (
      <Card bordered={false} bodyStyle={{ padding: 10 }}>
        <div className={styles.lineTitle} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div style={{ flex: "0 0 120px" }}>
            <img src={staticPath + "/homeImg/stat.png"} />
            <span style={{ marginRight: 5 }}>{formatMessage({ id: 'home.statisticsTitle' })}</span>
            <Tooltip
              title={formatMessage({ id: 'home.statisticsTooltip' })}
            >
              <Icon type="question-circle" />
            </Tooltip>
          </div>
          <div className={styles.dataDate}>
            <Form layout={'inline'}>
              <Form.Item style={{ textAlign: 'center' }}>
                <Button type="link" onClick={() => this.quickDate('1', 'days')}
                  style={{ color: startTime == moment().subtract("1", "days").format("YYYY-MM-DD") && endTime == moment().format("YYYY-MM-DD") ? '#3e5bff' : '#333333' }}
                >{formatMessage({ id: 'home.yesterday' })}</Button>
                <Button type="link" onClick={() => this.quickDate('7', 'days')}
                  style={{ color: startTime == moment().subtract("7", "days").format("YYYY-MM-DD") && endTime == moment().format("YYYY-MM-DD") ? '#3e5bff' : '#333333' }}
                >{formatMessage({ id: 'home.lastSevenDays' })}</Button>
                <Button type="link" onClick={() => this.quickDate('1', 'months')}
                  style={{ color: startTime == moment().subtract("1", "months").format("YYYY-MM-DD") && endTime == moment().format("YYYY-MM-DD") ? '#3e5bff' : '#333333' }}
                >{formatMessage({ id: 'home.lastMonth' })}</Button>
                {
                  getFieldDecorator('time', {
                    initialValue: [moment().subtract('1', 'days'), moment().subtract('1', 'days')]
                  })(
                    <DatePicker.RangePicker allowClear={false} style={{ width: '250px' }} />
                  )
                }
              </Form.Item>
              <Form.Item>
                {
                  currentUser.applicationId ? null : getFieldDecorator('applicationId', { initialValue: '0' })(
                    <Select placeholder={formatMessage({ id: 'home.selectApplication' })} style={{ width: 200 }}>
                      <Select.Option value={'0'}>{formatMessage({ id: 'home.allApplications' })}</Select.Option>
                      {
                        robotList.map(item => {
                          return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                        })
                      }
                    </Select>
                  )
                }
              </Form.Item>
              <Form.Item>
                {
                  getFieldDecorator('trigger', { initialValue: '' })(
                    <Select placeholder={formatMessage({ id: 'home.selectTriggerMethod' })} style={{ width: 200 }}>
                      <Select.Option value={''}>{formatMessage({ id: 'home.allTriggerMethods' })}</Select.Option>
                      <Select.Option value={1}>{formatMessage({ id: 'home.clickTrigger' })}</Select.Option>
                      <Select.Option value={2}>{formatMessage({ id: 'home.inputTrigger' })}</Select.Option>
                    </Select>
                  )
                }
              </Form.Item>
              <Form.Item>
                <Button type={'primary'} onClick={this.queryByConditions}>{formatMessage({ id: 'home.query' })}</Button>
              </Form.Item>
            </Form>
          </div>
        </div>
        <DataStatic loading={dataLoading} dataInfo={dataInfo} />
        <Row gutter={20}>
          <Col span={12}>
            <ChatStat loading={dataLoading} onRef={ref => this.ChatStat = ref} questionTypeList={questionTypeList} hotList={hotList} qaTotal={qaTotal} total={total} />
          </Col>
          <Col span={12}>
            <AccessTrends onRef={ref => this.AccessTrends = ref} />
          </Col>
        </Row>
      </Card>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(Home));
